package com.tjetc._1collection._1list;

public class _5LinkedListNode {
    // 模拟一个双向链表
    public static void main(String[] args) {
        // 创建三个节点
        Node zhangsan = new Node("zhangsan");
        Node lisi = new Node("lisi");
        Node wangwu = new Node("wangwu");

        // 给三个节点串起来
        // zhangsan -> lisi -> wangwu
        zhangsan.next = lisi;
        lisi.pre = zhangsan;
        lisi.next = wangwu;
        wangwu.pre = lisi;
        System.out.println(zhangsan.next); //node item=lisi

        // 创建头节点
        Node first = zhangsan;
        // 创建尾节点
        Node last = wangwu;

        // 正序遍历
        System.out.println("---------正序遍历");
        while (true) {
            if (first == null) {
                break;
            }
            System.out.println(first);
            first = first.next;
        }
        // 逆序遍历
        System.out.println("---------逆序遍历");
        while (true) {
            if (last == null) {
                break;
            }
            System.out.println(last);
            last = last.pre;
        }

        // 模拟插入一个节点
        // 体现双链表的增加和删除很方便
        Node zhaoliu = new Node("zhaoliu");
        // 将zhaoliu 插入到wangwu前
        lisi.next = zhaoliu;
        zhaoliu.next = wangwu;
        wangwu.pre = zhaoliu;
        zhaoliu.pre = lisi;

        first = zhangsan;
        last = wangwu;

        System.out.println("---------添加新元素后的遍历");

        while (true) {
            if (first == null) {
                break;
            }
            System.out.println(first);
            first = first.next;
        }
    }
}


// 模拟节点类
class Node {
    // 用来保存数据
    public Object item;
    // 存上一节点
    public Node pre;
    // 存下一节点
    public Node next;

    public Node(Object item) {
        this.item = item;
    }

    @Override
    public String toString() {
        return "node item=" + item;
    }
}
